/**
 * Created by jeryzym on 2017/6/30.
 */
define(['knockout',
        'platform.common',
        'bootbox',
        'knockout-bsTable',
        'knockout-jsTree',
        'knockout-component',
        'bootstrapValidator',
        'bootstrapValidator-zhCN',
        'sco.msg'],
    function (ko, platform, bootbox) {
        /**
         * 用于与服务端进行交互的方法
         * @type {{remove: remove, save: save, get: get, loadTreeNodes: loadTreeNodes, updateMenu: updateMenu}}
         */
        var rest = {
            remove: function (pid) {
                var param = {};
                param.menu_id = pid;
                platform.servicebreakAsync('~/rest/menu/delete', param, 'post')
                    .done(function (response) {
                        if (response instanceof Object && response.meta.success) {
                            platform.showOperTip('DELSUC');
                            viewModel.tableViewModel.refresh();
                            viewModel.refreshTree();
                        } else {
                            platform.showErrorTip(response.meta.message);
                        }
                    });
            },
            save: function (param) {
                platform.servicebreakAsync('~/rest/menu/save', param, 'post',
                    function () {
                        platform.showOperTip('dealing');
                    }).done(function (response) {
                    if (response instanceof Object && response.meta.success) {
                        platform.showOperTip('savesuc');
                        viewModel.tableViewModel.refresh();
                        viewModel.refreshTree();
                    }
                });
            },
            get: function (pid) {
                var param = {};
                param.menu_id = pid;
                var result = platform.servicebreak('~/rest/menu/selectOne', param).responseJSON;
                return result;
            },
            loadTreeNodes: function () {
                return platform.servicebreak('~/rest/menu/getTreeNodes', {nodeId: ''}).responseJSON;
            },
            updateMenu: function (param) {
                platform.servicebreakAsync('~/rest/menu/changeMenuPid', param,
                    'post', function () {
                        platform.showOperTip('dealing');
                    }).done(function (response) {
                    var result = response.responseJSON;
                    if (result instanceof Object && result.meta.success) {
                        platform.showOperTip('savesuc');
                        viewModel.tableViewModel.refresh();
                        viewModel.refreshTree();
                    }

                });
            }
        };
        var kbTable = require('knockout-bsTable');
        var jsTree = require('knockout-jsTree');

        var ViewModel = function () {
            var self = this;

            self.treeViewModel = new jsTree.jsTreeViewModel({
                core: {
                    data: {
                        url: platform.mapUrl('~/rest/menu/getTreeNodes?lazy'),
                        data: function (node) {
                            return JSON.stringify({'nodeId': node.id});
                        },
                        contentType: 'application/json',
                        dataType: 'json',
                        method: 'post'
                    }
                },
                plugins: ['wholerow']
            });
            self.selectedNode = ko.observable();
            self.onTreeNodeSelected = function (event, data) {

                var param = {};
                if (data.node.parent == '#') {
                    param.p_menu_id = '';
                    self.selectedNode('');
                } else {
                    param.p_menu_id = data.node.id;
                    self.selectedNode(data.node.id);
                }
                self.tableViewModel.refresh(param);
            };
            self.columns = [
                {
                    checkbox: true, field: 'checkbox', align: 'center', width: 30
                }, {
                    field: 'display_order',
                    title: '序号',
                    formatter: function (value, row, index) {
                        var options = self.tableViewModel.getOptions();
                        var indexPageNum = parseInt(options.pageNumber);
                        var indexPageSize = parseInt(options.pageSize);
                        return ((indexPageNum - 1) * indexPageSize)
                            + (index + 1);
                    },
                    width: 35,
                    align: 'center'
                }, {
                    field: 'menu_id', title: '主键标识', visible: false
                }, {
                    field: 'menu_name', title: '菜单名称', width: 240, align: 'left'
                }, {
                    field: 'menu_code', title: '快速启动编码'
                }, {
                    field: 'menu_uri', title: '链接地址', visible: false
                }, {
                    field: 'template_uri', title: '模板地址'
                }, {
                    field: 'script_uri', title: '模板脚本地址'
                }, {
                    field: 'icon_cls',
                    title: '菜单图标',
                    align: 'center',
                    width: 60,
                    formatter: function (value, row, index) {
                        return "<i class='" + value + "'></i>";
                    }
                }, {field: 'show_order', title: '显示顺序', align: 'right'}
            ];
            self.tableViewModel = new kbTable.bootstrapTableViewModel({
                url: platform.mapUrl('~/rest/menu/list'),
                toolbar: '#toolbar',
                queryParams: function (params) {
                    return {
                        pageNumber: params.offset / params.limit + 1,
                        pageSize: params.limit,
                        p_menu_id: ''
                    };
                },
                columns: self.columns
            });
            self.modalVisible = ko.observable(false);
            self.treeModalVisible = ko.observable(false);
            self.menuViewModel = {
                template: ko.observable('menuModalTemplate'),
                enabled: ko.observable(true),
                title: ko.observable(),
                menuId: ko.observable(),
                menuName: ko.observable(),
                menuCode: ko.observable(),
                menuUri: ko.observable(),
                templateUri: ko.observable(),
                scriptUri: ko.observable(),
                iconCls: ko.observable(),
                editStatus: ko.observable(),
                recordStatus: ko.observable(),
                pMenuId: ko.observable(),
                /**
                 * rest
                 */
                resetForm: function () {
                    $('#detailForm').resetForm();
                    if ($('#detailForm').data('bootstrapValidator') != null ||
                        $('#detailForm').data('bootstrapValidator') != undefined) {
                        $('#detailForm').data('bootstrapValidator').resetForm();
                    }

                    this.menuId('');
                    this.menuCode('');
                    this.menuName('');
                    this.menuUri('');
                    this.templateUri('');
                    this.scriptUri('');
                    this.pMenuId('');
                    this.iconCls('');
                    this.recordStatus('');
                    this.editStatus('');
                    this.enabled(true);
                },
                disableForm: function () {
                    $('#detailForm').find('input,textarea').attr('disabled', true);
                },
                enableForm: function () {
                    $('#detailForm').find('input,textarea').attr('disabled', false);
                },
                setFormData: function (menuId) {
                    var result = rest.get(menuId);
                    if (result instanceof Object && result.meta.success) {
                        var info = result.responseObject;

                        this.menuId(info.menu_id);
                        this.menuName(info.menu_name);
                        this.menuCode(info.menu_code);
                        this.iconCls(info.icon_cls);
                        this.menuUri(info.menu_uri);
                        this.templateUri(info.template_uri);
                        this.scriptUri(info.script_uri);
                    }
                },
                validateForm: function () {
                    $('#detailForm').bootstrapValidator({
                        message: 'This value is not valid',
                        feedbackIcons: {
                            valid: 'glyphicon glyphicon-ok',
                            invalid: 'glyphicon glyphicon-remove',
                            validating: 'glyphicon glyphicon-refresh'
                        },
                        excluded: [':disabled'],
                        fields: {
                            menuName: {
                                validators: {
                                    notEmpty: {
                                        message: '*菜单名称为必填字段,不可为空'
                                    },
                                    stringLength: {
                                        min: 0,
                                        max: 128,
                                        message: '菜单名称最多不超出128个字符!'
                                    }
                                }
                            },
                            menuCode: {
                                validators: {
                                    notEmpty: {
                                        message: '菜单编码为必填字段,不可为空'
                                    },
                                    stringLength: {
                                        min: 0,
                                        max: 50,
                                        message: '菜单编码最多不超出50个字符!'
                                    }
                                }
                            }, menuUri: {
                                validators: {
                                    stringLength: {
                                        min: 0,
                                        max: 256,
                                        message: '菜单地址最多不超出256个字符!'
                                    }
                                }
                            }, templateUri: {
                                validators: {
                                    stringLength: {
                                        min: 0,
                                        max: 256,
                                        message: '模板地址最多不超出256个字符!'
                                    }
                                }
                            }, scriptUri: {
                                validators: {
                                    stringLength: {
                                        min: 0,
                                        max: 256,
                                        message: '脚本地址最多不超出256个字符!'
                                    }
                                }
                            }
                        }
                    });
                },
                showNewForm: function (pid) {
                    this.resetForm();
                    this.validateForm();
                    this.enableForm();

                    this.title('新增菜单信息');
                    this.menuId(platform.uuid());
                    this.editStatus('0');
                    this.recordStatus('1');
                    this.iconCls('fa fa-ravelry');

                    if (pid !== undefined && pid !== null) {
                        this.pMenuId(pid);
                    } else {
                        this.pMenuId('');
                    }
                    self.modalVisible(true);
                },
                showEditForm: function (menuId) {
                    this.resetForm();
                    this.validateForm();
                    this.enableForm();

                    this.title("编辑菜单信息");
                    this.editStatus('1');
                    this.recordStatus('1');
                    this.setFormData(menuId);
                    self.modalVisible(true);
                },
                showViewForm: function (menuId) {
                    this.resetForm();
                    this.disableForm();
                    this.title('查看菜单信息');

                    this.setFormData(menuId);
                    this.enabled(false);
                    self.modalVisible(true);
                },
                save: function () {
                    $('#detailForm').data('bootstrapValidator').validate();
                    if (!$('#detailForm').data('bootstrapValidator').isValid()) {
                        platform.showOperTip('VALIDATEFAIL');
                        return;
                    }
                    var param = {};
                    param.menu_id = this.menuId();
                    param.menu_code = this.menuCode();
                    param.menu_name = this.menuName();
                    param.menu_uri = this.menuUri();
                    param.template_uri = this.templateUri();
                    param.script_uri = this.scriptUri();
                    param.icon_cls = this.iconCls();
                    param.edit_status = this.editStatus();

                    if (param.edit_status == '0') {
                        param.p_menu_id = this.pMenuId();
                        param.record_status = this.recordStatus();
                    } else if (param.edit_status == '1') {
                        param.record_status = this.recordStatus();
                    }
                    rest.save(param);
                },
                close: function () {
                    self.modalVisible(false);
                    $('#menuDialog').toggleClass('hide');
                }
            };
            self.moveTreeViewModel = {
                title: ko.observable(),
                init: function () {
                    this.title('选择目标菜单');
                    // $('#targetTree').empty();
                    $('#targetTree').jstree({
                        core: {
                            data: {
                                url: platform.mapUrl('~/rest/menu/getTreeNodes'),
                                data: function (node) {
                                    return JSON.stringify({'nodeId': node.id});
                                },
                                contentType: 'application/json',
                                dataType: 'json',
                                method: 'post'
                            }
                        },
                        plugins: ['wholerow']
                    })
                },
                confirm: function () {
                    var that = this;
                    var selectedNode = $('#targetTree').jstree(true).get_selected();
                    var selections = self.tableViewModel.getSelections();

                    var param = {};
                    param.menu_id = selections[0].menu_id;
                    if (selectedNode.length == 0) {
                        platform.confirm(
                            '<i class="fa fa-warning"></i>&nbsp;&nbsp;提示信息',
                            'small', '未选择父级节点,确认是否将数据变更为根级节点?', '确认', '取消',
                            function () {
                                rest.updateMenu(param);
                                that.close();

                            });
                    } else {
                        param.p_menu_id = selectedNode[0];

                        var node = $('#targetTree').jstree(true).get_node(selectedNode[0]);
                        if (node.parent == '#') {//迁移至根节点的做法
                            param.p_menu_id = '';
                        }
                        if (param.menu_id == param.p_menu_id) {
                            platform.showWarnTip('无法将选择节点迁移至自节点下');
                            return;
                        }
                        rest.updateMenu(param);
                        that.close();
                    }
                    //不能将菜单迁移至子节点及以下
                },
                close: function () {
                    self.treeModalVisible(false);
                    $('#moveDialog').toggleClass('hide');
                }
            };
            self.fnSearch = function () {

            };
            self.fnAdd = function () {
                if (self.selectedNode() == null) {
                    bootbox.confirm({
                        title: '<i class="fa fa-warning"></i>&nbsp;&nbsp;系统提示',
                        size: 'small',
                        message: '确认是否新增顶级菜单?',
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success btn-sm'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-default btn-sm'
                            }
                        },
                        callback: function (result) {
                            if (result) {
                                self.menuViewModel.showNewForm();
                                $('#menuDialog').toggleClass('hide');
                            }
                        }
                    });
                } else {
                    self.menuViewModel.showNewForm(self.selectedNode());
                    $('#menuDialog').toggleClass('hide');
                }

            };
            self.fnRemove = function () {
                var selections = self.tableViewModel.getSelections();
                if (selections == null || selections == undefined
                    || (selections instanceof Array && selections.length != 1)) {
                    platform.showTip('remove');
                    return;
                }
                bootbox.confirm({
                    title: '<i class="fa fa-warning"></i>&nbsp;&nbsp;删除提示信息',
                    size: 'small',
                    message: '删除存在子节点的数据时，将删除全部该节点下的数据，并解除角色与所删除菜单及子菜单的关系，确认是否删除?',
                    buttons: {
                        confirm: {
                            label: '确认',
                            className: 'btn-success btn-sm'
                        },
                        cancel: {
                            label: '取消',
                            className: 'btn-default btn-sm'
                        }
                    },
                    callback: function () {
                        var menu_id = selections[0].menu_id;
                        rest.remove(menu_id);
                    }
                });
            };
            self.fnEdit = function () {
                var selections = self.tableViewModel.getSelections();
                if (selections.length != 1) {
                    platform.showTip('EDIT');

                } else {
                    var menuId = selections[0].menu_id;
                    self.menuViewModel.showEditForm(menuId);
                    $('#menuDialog').toggleClass('hide');
                }

            };
            self.fnView = function () {
                var selections = self.tableViewModel.getSelections();
                if (selections.length != 1) {
                    platform.showTip('VIEW');
                } else {
                    var menuId = selections[0].menu_id;
                    self.menuViewModel.showViewForm(menuId);
                    $('#menuDialog').toggleClass('hide');
                }
            };
            self.fnMove = function () {
                var selections = self.tableViewModel.getSelections();
                if (selections.length != 1) {
                    platform.showTip('move');
                } else {
                    self.moveTreeViewModel.init();
                    self.treeModalVisible(true);
                    $('#moveDialog').toggleClass('hide');
                }

            };
            self.refreshTree = function () {
                var nodes = rest.loadTreeNodes();
                self.treeViewModel.refresh(nodes);
            }
        };

        var viewModel = new ViewModel();
        return viewModel;
    });